package concurrent.thread.singleton;

import org.junit.Test;

public class SingletonTest {

	/**
	 * 懒汉单例
	 * <p>
	 * 单线程情况下，该懒汉单例模式不会出现问题
	 */
	@Test
	public void lanHanTest() {
		// 这里的 == 是比较内存地址
		System.out.println(LanHanSingletonInstance.getInstance() == LanHanSingletonInstance.getInstance());
		System.out.println(LanHanSingletonInstance.getInstance() == LanHanSingletonInstance.getInstance());
		System.out.println(LanHanSingletonInstance.getInstance() == LanHanSingletonInstance.getInstance());
		System.out.println(LanHanSingletonInstance.getInstance() == LanHanSingletonInstance.getInstance());
	}

	/**
	 * 多线程情况下，不加锁，懒汉模式
	 */
	@Test
	public void multiLanHanTest() {
		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				LanHanSingletonInstance.getInstance();
			}).start();
		}
	}

	/**
	 * 多线程情况下，加锁，懒汉模式
	 */
	@Test
	public void suoMultiLanHanTest() {
		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				LanHanSingletonInstance.suoGetInstance();
			}).start();
		}
	}

	/**
	 * 多线程情况下，双重检测锁，懒汉模式
	 */
	@Test
	public void DoubleCheckLockMultiLanHanTest() {
		for (int i = 0; i < 1000; i++) {
			new Thread(() -> {
				DoubleCheckLockingSingletonInstance.getInstance();
			}).start();
		}
	}

}
